﻿/// <reference path="jquery-1.4.1-vsdoc.js"/>

// this function is fired when the document is in the ready state.
function documentLoad() {
    $('#tabs').append("<ul></ul>").tabs().bind('tabsselect', function(event, ui) {

        if ((ui.tab.toString().replace("#", "")) == "Add") {
            return AddPage("New Page", "shailensukul", "2");
        }
    });
    
    /* Load the user's pages */
    
    LoadPages("shailensukul");
    LoadWidgetList();
    
}

function LoadWidgetList() {
    CallWebService(widgetAllUrl, '',
        function(result) {
            var response = JSON.parse(result.d);
            if (response.IsSuccess) {
                LoadAllWidgets(response.Payload);
            }
            else {
                ShowErrorMessage(response);
                return false;
            }
        });
}

function LoadAllWidgets(allWidgets) {
    var h = "";
    for (var i = 0; i < allWidgets.length; i++) {
        h += "<div>" + allWidgets[i].Name + "</div>";
    }       
    $("#widgetListBody").html(h);

}

function ShowWidgets() {
    $("#widgetList").dialog({ 'modal': true, 'closeOnEscape': true, 'resizable': false,
        width: 700,
        height: 'auto',
        open: function(event, ui) { $("#widgetListBody").css({ visibility: "visible" }); },
        buttons:
            { "Cancel": function() { $(this).dialog("close"); $(this).dialog("destroy"); $("#widgetListBody").css({ visibility: "hidden" }); },
                "Ok": function() { }
            }
    });
}

/* Load all pages for the user */
function LoadPages(username) {
    var input = { "username": username };
    /* Remove any existing tabs */    
    var abCount=$('#tabs').tabs('length')
    while (abCount>0) {
        abCount--;
        $('#tabs').tabs('remove', abCount);
    }
    CallWebService(widgetGetPagesUrl, input,
    function(result) {
        var response = JSON.parse(result.d);
        if (response.IsSuccess) {
            for (var i = 0; i < response.Payload.length; i++) {
                /* Add the pages as tabs */
                AddTab(response.Payload[i], i);

                /* Add the widgets for the page */
                /* Load widgets for the first page */
                LoadWidgets(response.Payload[i].ID, response.Payload[i].Layout.Name);
            }
            /* Add the plus tab */
            $('#tabs').tabs('add', "#Add", "<div class='PlusSmall'>" +
            "<img src='/images/plus_icon.png'" +
            //" onclick='AddPage(\"New Page\", \"shailensukul\", \"2\")'" +
            "/></div>");
        }
        else {
            ShowErrorMessage(response);
        }
    });
}

/* Adds a new tab page */
function AddPage(title, username, layoutType) {
    /* Call the web service to add a page */
    var input = { title: title, username: username, layoutType: layoutType };
    var tabIndex = $('#tabs').tabs('length');
    /* Do not allow unlimited tabs */
    if (tabIndex > 4) {
        alert("Only 4 pages are allowed");
        // select the previous tab if there is one
        if (tabIndex != 0) {
            //$('#tabs').tabs('select', parseInt((tabIndex - 1)));
        }
        return false;
    }
    CallWebService(widgetCreatePageUrl, input,
        function(result) {
            var response = JSON.parse(result.d);
            if (response.IsSuccess) {
                /* Add the page as the last tab */
                tabIndex = tabIndex - 1;
                AddTab(response.Payload, tabIndex);
                /* Add the widgets for the page */
                LoadWidgets(response.Payload.ID, response.Payload.Layout.Name);
                /* Select the new tab */
                $('#tabs').tabs('select', '#' + response.Payload.ID);
            }
            else {
                ShowErrorMessage(response);
                return false;
            }
        });
        return true;
}

/* Deletes a tab page */
function DeletePage(pageId, tIndex) {
    if (confirm("Do you want to delete this page?")) {
        var input = { pageId: pageId };
        CallWebService(widgetDeletePageUrl,
                        input,
                        function(result) {
                            var response = JSON.parse(result.d);
                            if (response.IsSuccess) {
                                var selectedTab = $("#tabs").tabs('length')-2;
                                if (selectedTab != 1) { selectedTab--; }
                                $("#tabs").tabs('select', selectedTab);
                                $("#tabs").tabs('remove', tIndex);
                            }
                            else {
                                ShowErrorMessage(response);
                            }
                        }
        );
    }
}

/* Add the page as a tab */
function AddTab(page, tabIndex) {
    $('#tabs').tabs('add',
                        ("#" + page.ID),
                        "<span id='spn" + page.ID + "'" + " pageLayout='" + page.Layout.Id + "'>" + page.Title  + "</span>" +
                        "<img src='/images/edit.png' class='tabImage' alt='Edit' id='img_Edit_" + page.ID + "'/>" +
                        "<img src='/images/close.png' class='tabImage' alt='Close' id='img_Close_" + page.ID + "'/>",
                        tabIndex);

    $("#img_Close_" + page.ID).click(function() { DeletePage(page.ID, tabIndex); });
    $("#img_Edit_" + page.ID).click(function() { EditPage(page); });
}

function EditPage(page) {

        var editDialog = $("#divEdit");  
        $("#divEdit").css( { visibility : "visible"} );
        $("#txtEditPageTitle").attr("value", $("#spn" + page.ID).html());

        var o = $("#optPageLayout")[0];
        for (var i=0;i<o.length;i++) {
            o[i].selected = (o[i].value == page.Layout.Id);
        }

        $("#divEdit").dialog({ 'modal': true, 'closeOnEscape': true, 'resizable': false,
            open: function(event, ui) { $("#txtEditPageTitle").focus(); },
            buttons:
        { "Cancel": function() { $(this).dialog("close"); $(this).dialog("destroy"); $("#divEdit").css({ visibility: "hidden" }); },
            "Save": function() {
                // get the selected layout
                var layoutId = $("#optPageLayout").val();
                var input = { pageId: page.ID, title: $("#txtEditPageTitle").attr("value"), username: "shailensukul", layoutId: layoutId };
                $("#divEdit").css({ visibility: "hidden" });
                CallWebService(widgetEditPageUrl,
                       input,
                        function(result) {
                            var response = JSON.parse(result.d);
                            if (response.IsSuccess) {
                                if (page.Layout.Id != $("#optPageLayout").val()) {
                                    LoadPages("shailensukul");
                                } else {
                                    page.Title = $("#txtEditPageTitle").attr("value");
                                    $(("#spn" + page.ID))[0].innerHTML = $("#txtEditPageTitle").attr("value");
                                }
                            }
                            else {
                                ShowErrorMessage(response);
                            }
                        }
            );
                $(this).innerHTML = "";
                $(this).dialog("close");
                $(this).dialog("destroy");
            }
        }
        });
}

function LoadWidgets(pageId, layoutName) {
    /* Determine the column cutoff */
    var maxCol = 1;
    var colWidth = "100%";
    var col = 1;
    switch (layoutName) {
        case "1X1":
            maxCol = 1;
            colWidth = "100%";
            break;
        case "2X2":
            maxCol = 2;
            colWidth = "50%";
            break;
        case "3X3":
            maxCol = 3;
            colWidth = "33%";
            break;
        case "4X4":
            maxCol = 4;
            colWidth = "25%";
            break;
        default:
            maxCol = 1;
            colWidth = "100%";
            break;
    }
    var input = { "pageId": pageId };
    CallWebService(widgetGetWidgetUrl, input,
    function(result) {
        var response = JSON.parse(result.d);
        if (response.IsSuccess) {
            /* Build a table of widgets */
            if (response.Payload.length > 0) {
                var body = "<table id=\"widgetTable\">";
                body += "<tbody>";
                for (var i = 0; i < response.Payload.length; i++) {
                    if (col == 1) { body += "<tr>"; }
                    //                    body += "<td style=\"width:" + colWidth + "\">";
                    body += "<td>";
                    body += "<div class='widgetDroppable' style='width:98%'>";
                    body += "<div id=\"" + response.Payload[i].Id.toString() +
                            "\" order=\"" + response.Payload[i].OrderNo.toString() + "\"" +
                            " class='widgetDraggable'>";
                    body += "<div class=\"ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix ui-resizable-disabled\">";

                    body += "<span class=\"ui-dialog-title\">" + response.Payload[i].Title + "</span>";

                    /* Close */
                    body += "<a class=\"ui-dialog-titlebar-close ui-corner-all\" href=\"#\">";
                    body += "<span class=\"" + pageId + "dialogClose ui-icon ui-icon-closethick\">close</span></a>";

                    /* Minimize */
                    body += "<a class=\"ui-corner-all\" href=\"#\">";
                    body += "<span id=\"spnMin_" + response.Payload[i].Id +
                    "\" widgetId=\"" + response.Payload[i].Id.toString() + "\" state=\"min\" class=\"" + pageId + "dialogMin dialogMin ui-icon ui-icon-carat-1-s\" style=\"float: right;right:30px;position: relative;\">mimimize</span></a>";

                    /* Maximize */
                    body += "<a class=\"ui-corner-all\" href=\"#\">";
                    body += "<span class=\"" + pageId + "dialogMax dialogMax ui-icon ui-icon-extlink\" style=\"float: right;right:30px;position: relative;\"";
                    body += " widgetId = \"" + response.Payload[i].Id.toString() + "\" title=\"" + response.Payload[i].Title + "\">";
                    body += "maximize</span></a>";

                    body += "</div>";
                    body += "<div class=\"ui-dialog-content ui-widget-content\">";
                    body += "<div id=\"widget_" + response.Payload[i].Id.toString() + "\" style='border: solid 1px black'>";
                    body += response.Payload[i].Widget.Body;
                    body += "</div>";
                    body += "</div>";
                    body += "</div>";
                    body += "</div>";
                    body += "</td>";

                    /* if we have reached the end and there are blank columns */
                    if (col < maxCol && i == (response.Payload.length - 1)) {
                        for (var j = col; j < maxCol; j++) {
                            if (j == col) {
                                //body += "<td class=\"widgetBlank\" style=\"width:" + colWidth + "\"><div class='Plus' onclick='ShowWidgets()'>";
                                body += "<td class='widgetBlank'>"
                                //body += "<div class='Plus' onclick='ShowWidgets()'>";
                                body += "<img src='/images/plus.png' alt='Add Widget' class='Plus' onclick='ShowWidgets()'/>";
                                body += "</div></td>";
                            } else {
                                //body += "<td class=\"widgetBlank\" style='width:" + colWidth + "'>";
                                body += "<td class='widgetBlank'>";
                                body += "</td>";
                            }
                        }
                    }

                    col++;
                    if (col > maxCol || i == (response.Payload.length - 1))
                    { body += "</tr>"; col = 1; }
                }
                body += "</tbody>";
                body += "</table>";

                $(("#" + pageId.toString())).innerHTML = "";
                $(("#" + pageId.toString())).append(body);
                AttachEventHandlers(pageId);
                $(".widgetDraggable").draggable({
                    opacity: 0.35,
                    revert: 'invalid', // when not dropped, the item will revert back to its initial position
                    helper: 'clone',
                    containment: 'document'
                   
                });

                $(".widgetDroppable").droppable({
                    activeClass: 'droppable-active',
                    hoverClass: 'ui-state-active',
                    drop: function(ev, ui) {
                        exchangeItem(ui.draggable, $(this));
                    }
                });
            }
        }
        else {
            ShowErrorMessage(response);
        }
    });
}

function exchangeItem($item, $dest) {
    var $dest2 = $item[0].parentElement;
    $dest2 = $($dest2);

    var $item2 = $($dest).find('.widgetDraggable');
    $item2 = $($item2);

    var oldOrder = $item.attr('order');
    $item.attr('order', $item2.attr('order'))
    $item2.attr('order', oldOrder);

    $item.appendTo($dest).fadeIn(function() {
        $item.animate({ width: $item.width() });
    });

    $item2.appendTo($dest2).fadeIn(function() {
        $item2.animate({ width: $item2.width() });
    });
//        alert("Swapping positions: " + $item.attr('order') + " and " + $item2.attr('order'));
}

function AttachEventHandlers(pageId) {
    $("." + pageId + "dialogClose").click(function() {
        var answer = confirm("Do you want to close this widget?");
    });

    $("." + pageId + "dialogMin").click(function() {
        if (this.state == "min") {
            this.state = "max";
            $("#spnMin_" + this.widgetId).removeClass(".ui-icon ui-icon-carat-1-s").addClass(".ui-icon ui-icon-carat-1-n");
            $("#widget_" + this.widgetId).hide();
        }
        else {
            this.state = "min";
            $("#spnMin_" + this.widgetId).removeClass(".ui-icon ui-icon-carat-1-n").addClass(".ui-icon ui-icon-carat-1-s");
            $("#widget_" + this.widgetId).show();
        }
    });

    $("." + pageId + "dialogMax").click(function() {
        $("<div id=\"zoomedDialog\"></div>").append($("#widget_" + this.widgetId)[0].innerHTML).dialog({
            width: 400,
            height: 360,
            show: "slow",
            hide: "slow",
            title: this.title,
            close: function() { $("#zoomedDialog").dialog('destroy'); }
        });
        $(("#" + this.widgetId)).dialog('open');
    });
}